package com.meila.cms.controller;

import com.alibaba.fastjson.JSONObject;
import com.github.miemiedev.mybatis.paginator.domain.PageBounds;
import com.google.common.collect.Lists;
import com.meila.cms.common.basic.util.PinyinUtil;
import com.meila.cms.common.constants.AttachmentConstants;
import com.meila.cms.common.page.PageBoundsUtil;
import com.meila.cms.common.page.Pager;
import com.meila.cms.common.page.SystemContext;
import com.meila.cms.model.*;
import com.meila.cms.services.topic.IAttachmentService;
import com.meila.cms.services.topic.IChannelService;
import com.meila.cms.services.topic.ITopicService;
import com.meila.cms.thirdParty.spider.GakkiBlogProcessor;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import us.codecraft.webmagic.Spider;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.nio.file.Path;
import java.util.List;

/**
 * Created by meila-x on 2015/12/22.
 */
@Controller
@RequestMapping("blog")
public class BlogController {
    private static final Logger logger = Logger.getLogger(BlogController.class);

    private ITopicService topicService;

    @Autowired
    private IChannelService channelService;

    @Autowired
    private IAttachmentService attachmentService;

    @Value("${realpath}")
    String localPath;

    public ITopicService getTopicService() {
        return topicService;
    }

    @Inject
    public void setTopicService(ITopicService topicService) {
        this.topicService = topicService;
    }

    @RequestMapping("/index")
    public String index(Model model) {
        logger.info("BlogIndexController /blog/index");

        List<Topic> datas = topicService.listTopicByChannel(36, "5");

        //获取最新的5条文章
        List<Topic> latestTopics = topicService.listLatestTopics(8, "");
        logger.info("latestTopics=" + JSONObject.toJSONString(latestTopics));

        //获取点击数最高的5条文章
        List<Topic> mostClickTopics = topicService.listMostClickTopics(5);
        logger.info("mostClickTopics=" + JSONObject.toJSONString(mostClickTopics));


        model.addAttribute("datas", datas);
        model.addAttribute("latestTopics", latestTopics);
        model.addAttribute("mostClickTopics", mostClickTopics);
        return "blog/index";
    }

    /**
     * 跳转到about页面about.jsp
     *
     * @return
     */
    @RequestMapping("/about")
    public String jump2AboutPage() {
        logger.info("个人介绍页面开始");
        return "blog/about";
    }

    /**
     * 跳转到shuo.jsp
     *
     * @return
     */
    @RequestMapping("/shuo")
    public String jump2ShuoPage() {
        return "blog/shuo";
    }

    /**
     * 跳转到日记页面 riji.jsp
     *
     * @return
     */
    @RequestMapping("/riji")
    public String jump2rijiPage() {
        return "blog/riji";
    }


    /**
     * 跳转到学习页面 learn.jsp
     *
     * @return
     */
    @RequestMapping("/learn")
    public String jump2learnPage() {
        return "blog/learn";
    }

    /**
     * 跳转到访客统计页面 guestbook.jsp
     *
     * @return
     */
    @RequestMapping("/guestbook")
    public String jump2guestbookPage() {
        return "blog/guestbook";
    }

    @RequestMapping("/spider/add")
    public String spiderAddCtrl(Model model) {
        logger.warn("BlogIndexController /blog/index");
        Spider.create(new GakkiBlogProcessor()).addPipeline(topicService).thread(5).run();
        List<Topic> datas = topicService.listTopicByChannel(36, "5");
        model.addAttribute("datas", datas);
        return "blog/index";
    }

    @RequestMapping("/jump2ContentPage/{artId}")
    public String jump2ContentPage(@PathVariable("artId") String artId, Model model, HttpServletRequest request) {

        logger.info("跳转到文章内容模版，填充对应页面内容开始...");
        model.addAttribute("artId", artId);

        return "blog/content";

    }


    @RequestMapping("/tpl/web/about")
    public String jump_web_about(Model model) {
        logger.info("获取心情点滴列表信息开始...");
        try {
            //TODO 定时任务，定时从本地文件夹拷贝附件到项目工程目录下
            int cid = 39;
            getNavListInfo(model, cid, "关于我");
        } catch (Exception e) {
            logger.error("程序异常:", e);
            throw new CmsException(e.getMessage(), e.getCause());
        } finally {
            return "tpl/web/about";
        }
    }

    @RequestMapping("/tpl/web/index")
    public String jump_web_index(Model model) {
        logger.info("首页进入！！！");

        List<Topic> datas = topicService.listTopicByChannel(43, "5");

        //获取最新的5条文章
        List<Topic> latestTopics = topicService.listLatestTopics(8, "");
        logger.info("latestTopics=" + JSONObject.toJSONString(latestTopics));

        //获取点击数最高的5条文章
        List<Topic> mostClickTopics = topicService.listMostClickTopics(5);
        logger.info("mostClickTopics=" + JSONObject.toJSONString(mostClickTopics));

        //获取友情链接
        List<Topic> links = topicService.listTopicByChannel(44, "5");

        logger.info("获取导航条相关信息开始...");
        List<Channel> navChannels = channelService.listByParent(36);

        for (Channel c : navChannels) {
            String pinyinStr = PinyinUtil.str2Pinyin(c.getName(), null);
            c.setPinyinStr(pinyinStr);
        }


        model.addAttribute("datas", datas);
        model.addAttribute("links", links);
        model.addAttribute("latestTopics", latestTopics);
        model.addAttribute("mostClickTopics", mostClickTopics);
        model.addAttribute("navChannels", navChannels);

        return "tpl/web/index";
    }

    @RequestMapping("/tpl/web/caselist")
    public String jump_web_caselist() {
        return "tpl/web/caselist";
    }

    @RequestMapping("/tpl/web/knowledge")
    public String jump_web_knowledge() {
        return "tpl/web/knowledge";
    }

    /**
     * 获取心情点滴信息列表，分页，并且配图
     *
     * @return
     */
    @RequestMapping("/tpl/web/moodlist")
    public String jump_web_moodlist(Model model) {
        logger.info("获取心情点滴列表信息开始...");
        try {
            //TODO 定时任务，定时从本地文件夹拷贝附件到项目工程目录下
            int cid = 39;
            getNavListInfo(model, cid, "心情点滴");
        } catch (Exception e) {
            logger.error("程序异常:", e);
            throw new CmsException(e.getMessage(), e.getCause());
        } finally {
            return "tpl/web/moodlist";
        }
    }

    @RequestMapping("/tpl/web/new")
    public String jump_web_new() {
        return "tpl/web/new";
    }


    @RequestMapping("/tpl/web/newlist")
    public String jump_web_newlist(Model model) {
        logger.info("获取业界资讯列表信息开始...");
        try {
            int cid = 38;
            logger.info("获取最新的5条文章开始...");
            List<Topic> latestTopics = topicService.listLatestTopics(8, "");
            logger.info("latestTopics=" + JSONObject.toJSONString(latestTopics));

            logger.info("获取点击数最高的5条文章开始...");
            List<Topic> mostClickTopics = topicService.listMostClickTopics(5);
            logger.info("mostClickTopics=" + JSONObject.toJSONString(mostClickTopics));

            model.addAttribute("mostClickTopics", mostClickTopics);
            model.addAttribute("latestTopics", latestTopics);

            getNavListInfo(model, cid, "业界资讯");
        } catch (Exception e) {
            logger.error("程序异常:", e);
            throw new CmsException(e.getMessage(), e.getCause());
        } finally {
            return "tpl/web/newlist";
        }
    }

    private void getNavListInfo(Model model, int cid, String cName) throws IOException, IllegalAccessException, InvocationTargetException {

        //进行文件的存储
        String realPath = SystemContext.getRealPath();
        logger.info("获取到的文件真实路径realPath:" + realPath);
        //附件上传的路径
        String path = realPath + AttachmentConstants.UPLOADPATH;
        logger.info("获取到的文件上传路径uploadpath:" + path);
        //图片缩略图存放路径
        String thumbPath = realPath + AttachmentConstants.THUMBNAIL;
        logger.info("获取到的文件缩略图存放路径thumbnail:" + thumbPath);

        FileUtils.copyDirectory(new File(localPath + "/"), new File(path));
        logger.info("拷贝图片结束...");
        Pager<Topic> page = topicService.find(cid, null, 1);
        List<Topic> list = page.getDatas();
        List<TopicVO> tempList = Lists.newArrayList();
        Pager<TopicVO> pages = null;
        for (Topic topic : list) {
            TopicVO vo = new TopicVO();
            BeanUtils.copyProperties(vo, topic);
            if (StringUtils.isNotBlank(topic.getPreViewImg())) {
                vo.setAttachFileName(topic.getPreViewImg());
            }
            tempList.add(vo);
        }
        if (CollectionUtils.isEmpty(tempList)) {
            logger.info("没有获取到" + cName + "记录");
        } else {
            logger.info("TopicList:" + JSONObject.toJSONString(tempList) + "");
            List<Attachment> attachmentList = attachmentService.findChannelPic(cid);
            model.addAttribute("attachList", attachmentList);
            if (CollectionUtils.isEmpty(attachmentList)) {
                logger.info(cName + "栏目下的文章都没有附件图片");
            } else {
                logger.info("获取附件信息开始...");
                for (TopicVO topic : tempList) {
                    for (Attachment attachment : attachmentList) {
                        if (attachment.getTid() == topic.getId()) {
                            topic.setAttachFileName(attachment.getNewName());
                            logger.info("文章id:" + topic.getId() + "的附件图片名为:" + attachment.getNewName());
                            continue;
                        }
                    }
                }
            }
        }
        pages = new Pager<TopicVO>((int) page.getTotal(), tempList);
        pages.setSize(12);
        model.addAttribute("datas", pages);
        logger.info("获取" + cName + "列表结束...");

        logger.info("获取导航条相关信息开始...");
        List<Channel> navChannels = channelService.listByParent(36);
        for (Channel c : navChannels) {
            String pinyinStr = PinyinUtil.str2Pinyin(c.getName(), null);
            c.setPinyinStr(pinyinStr);
        }
        model.addAttribute("navChannels", navChannels);
    }

    @RequestMapping("/tpl/web/share")
    public String jump_web_share(Model model) {
        logger.info("获取句子迷列表信息开始...");
        try {
            int cid = 40;
            logger.info("获取最新的5条文章开始...");
            List<Topic> latestTopics = topicService.listLatestTopics(8, "");
            logger.info("latestTopics=" + JSONObject.toJSONString(latestTopics));

            logger.info("获取点击数最高的5条文章开始...");
            List<Topic> mostClickTopics = topicService.listMostClickTopics(5);
            logger.info("mostClickTopics=" + JSONObject.toJSONString(mostClickTopics));

            model.addAttribute("mostClickTopics", mostClickTopics);
            model.addAttribute("latestTopics", latestTopics);

            getNavListInfo(model, cid, "句子迷");
        } catch (Exception e) {
            logger.error("程序异常:", e);
            throw new CmsException(e.getMessage(), e.getCause());
        } finally {
            return "tpl/web/share";
        }
    }

    @RequestMapping("/tpl/web/template/{id}")
    public String jump_web_template(@PathVariable("id") String id, Model model) {
        logger.info(id);
        Topic topic = topicService.findById(id);
        logger.info("进入之前先更新文章点击数开始...");
        String clickNum = StringUtils.isBlank(topic.getClickNum()) ? "0" : topic.getClickNum();
        topic.setClickNum(String.valueOf(Integer.parseInt(clickNum) + 1));
        topicService.update(topic, topic.getCid());
        String keyWord = StringUtils.isBlank(topic.getKeyword())?" ":topic.getKeyword();
        String[] keyWordWhere = keyWord.split("\\|");
        List<String> keyWordList = Lists.newArrayList();
        for (int i = 0; i < keyWordWhere.length; i++) {
            keyWordList.add(keyWordWhere[i]);
        }
        keyWord = StringUtils.isBlank(keyWord) ? "" : keyWord.replaceAll("\\|", " ");
        topic.setKeyword(keyWord);
        logger.info("topic:" + JSONObject.toJSONString(topic));

        List<Topic> latestTopics = topicService.listLatestTopics(8, String.valueOf(topic.getCid()));
        logger.info("获取点击数最多的文章列表开始...");
        List<Topic> mostClickTopics = topicService.listMostClickTopics(5);

        logger.info("获取相关类似文章开始...");
        List<Topic> relativeTopics = topicService.listRelativeTopics(6, keyWordList, topic.getId());

        logger.info("获取上一篇，下一篇文章开始...");
        Topic preTopic = topicService.findById(String.valueOf(Integer.parseInt(id) - 1));
        Topic nextTopic = topicService.findById(String.valueOf(Integer.parseInt(id) + 1));

        logger.info("获取导航条相关信息开始...");
        List<Channel> navChannels = channelService.listByParent(36);

        List<Channel> channels = getChannels(topic, navChannels);


        model.addAttribute("topic", topic);
        model.addAttribute("latestTopics", latestTopics);
        model.addAttribute("mostClickTopics", mostClickTopics);
        model.addAttribute("relativeTopics", relativeTopics);
        model.addAttribute("preTopic", preTopic);
        model.addAttribute("nextTopic", nextTopic);
        model.addAttribute("channels", channels);
        model.addAttribute("navChannels", navChannels);
        return "tpl/web/template";
    }

    private List<Channel> getChannels(Topic topic, List<Channel> navChannels) {
        logger.info("获取面包屑地址导航相关信息开始...");
        List<Channel> channels = Lists.newArrayList();
        int cid = topic.getCid();
        Channel channel = channelService.load(cid);
        channels.add(channel);

        Channel channel_p = channelService.load(channel.getPid());
        channels.add(channel_p);

        Channel channel_pp = channelService.load(channel_p.getPid());
        if (channel_pp != null) {
            channels.add(channel_pp);
        }
        for (Channel c : navChannels) {
            String pinyinStr = PinyinUtil.str2Pinyin(c.getName(), null);
            c.setPinyinStr(pinyinStr);
        }
        return channels;
    }

    @RequestMapping("/tpl/web/test")
    public String jump_web_test() {
        logger.info("hello world!!!");
        return "tpl/web/template";
    }

    /**
     * 跳转到相册页面 xc.jsp
     *
     * @return
     */
    @RequestMapping("/tpl/web/xc")
    public String jump2xcPage(Model model) {
        logger.info("获取相册列表信息开始...");
        try {
            int cid = 41;
//            logger.info("获取最新的5条文章开始...");
//            List<Topic> latestTopics = topicService.listLatestTopics(8, "");
//            logger.info("latestTopics=" + JSONObject.toJSONString(latestTopics));
//
//            logger.info("获取点击数最高的5条文章开始...");
//            List<Topic> mostClickTopics = topicService.listMostClickTopics(5);
//            logger.info("mostClickTopics=" + JSONObject.toJSONString(mostClickTopics));
//
//            model.addAttribute("mostClickTopics", mostClickTopics);
//            model.addAttribute("latestTopics", latestTopics);

            getNavListInfo(model, cid, "相册");
        } catch (Exception e) {
            logger.error("程序异常:", e);
            throw new CmsException(e.getMessage(), e.getCause());
        } finally {
            return "tpl/web/xc";
        }
    }


}
